<!--
 * @Author: swc shanwenchao12138@163.com
 * @Date: 2025-02-24 14:56:57
 * @LastEditors: swc shanwenchao12138@163.com
 * @LastEditTime: 2025-03-04 14:37:15
 * @FilePath: \xf\src\components\base\modal\o-interaction\unitePanel.vue
 * @Description: 
 * @Version: 2.0
 * @Autor: swc
-->
<template>
  <div class="unitepanel-container">
    <div class="unite-panel">
      <Tabs v-if="layoutStyle === 'tabs'">
        <TabPane
          :label="$srv.getI18nBySrv(panel.name)"
          v-for="(panel, idx) in panels"
          :key="idx"
        >
          <layout-setter
            :compBoxInfo="compBoxInfo"
            :busEvent="busEvent"
            :config="panel.config"
          ></layout-setter>
        </TabPane>
      </Tabs>
      <Collapse :style="collapseStyle" v-else>
        <Panel v-for="(panel, idx) in panels" :key="idx">
          {{ $srv.getI18nBySrv(panel.name) }}
          <template #content
            ><layout-setter
              :compBoxInfo="compBoxInfo"
              :busEvent="busEvent"
              :config="panel.config"
            ></layout-setter>
          </template>
        </Panel>
      </Collapse>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  layoutSetter
} from './config';

@T_srv.comp({ name: 'unitePanel', components: { layoutSetter } })
export default class unitePanel extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  config: any;

  /* 组件名 */
  private name: string = 'unitePanel';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 一个组件要调用多个相同组件时,组件箱内引用实例冲突,在此要定义实例变量接收,并在方法里加get 和 set  */
  // private GT_???CompBoxInfo : ifs.I_compBoxInfo;
  // private GT_???CompBoxInfo : ifs.I_compBoxInfo;
  // public get???CompBoxInfo(): ifs.I_compBoxInfo{
  //   return this.GT_compBoxInfo
  // }

  // public set???CompBoxInfo(e :ifs.I_compBoxInfo):void{
  //   this.GT_compBoxInfo = e
  // }

  private layoutStyle: 'tabs' | 'collapse' = 'tabs';

  private panels: Array<any> = [];

  private collapseStyle: any = {
    '--collapseHeight': '100%',
    '--collapseWidth': '100%'
  };

  private busEvent: any = {
    main: '',
    deputy: Tsrv.utils.custUUID(8, 16)
  };

  private panelsData: Map<string, any> = new Map();

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);

    /* 最终应用组件向外抛出引用实例,以供应用间调用 */
    // Tsrv.compBox.addCompMergeName(
    //   Tsrv.compBox.getDefGUID(), // 全局compBox
    //   '????',
    //   this,
    //   '???'
    // );
    this.$bus.$on(this.busEvent.deputy, (e: object) => {
      this.handlePanelsData(e);
    });
  }

  public getData() {
    this.$bus.$emit(this.busEvent.main, true);
  }

  private handlePanelsData(d: object) {
    if (Tsrv.utils.isPlainObject(d)) {
      Object.keys(d).forEach(key => {
        this.panelsData.set(key, d[key]);
      });
    }
    const data = {};
    for (const [key, value] of this.panelsData) {
      data[key] = value;
    }
    this.$emit('on-update', data);
  }

  private init() {
    this.busEvent.main = this.config?.workID ?? Tsrv.utils.custUUID(8, 16);
    if (!Tsrv.noValue(this.config?.layoutStyle)) {
      this.layoutStyle = this.config.layoutStyle;
    }
    if (!Tsrv.noValue(this.config?.style)) {
      if (this.config.style.height !== 'auto') {
        this.collapseStyle['--collapseHeight'] =
          this.config.style.height - 180 > 50
            ? `${this.config.style.height - 180}px`
            : '50px';
      }
      this.collapseStyle['--collapseWidth'] = `${this.config.style.width}px`;
    }
    // 获取 布局信息
    this.getLayout();
  }

  /**
   * 获取 布局信息
   */
  public getLayout() {
    const panels = this.config.panels;
    const layoutIds = Object.keys(panels).map((g: string) => {
      return panels[g].layoutID;
    });
    const dbType = Tsrv.globalVar.dbType.MYSQL;
    const tableName = Tsrv.globalVar.tableName.SYS_LAYOUT;
    const gpd = new ts.T_getPartDataArg();
    gpd.setFunName(tableName).setLang(this.$i18n.locale || 'en-US');
    gpd.setPage(1, 99999).setDbType(dbType);
    gpd.setFilter({
      title: { $in: [...layoutIds] }
    });
    Tsrv.getData<any, ifs.I_getPartDataArg>(gpd)
      .then(([b, res, rows, msg]) => {
        if (!b) {
          msg && this.$msg(msg);
        }
        if (rows.length > 0) {
          this.handlePanelsConfig(rows);
        } else {
          this.$msg(Tsrv.getI18nByValue('无此布局信息'));
        }
      })
      .catch((err: any) => {
        console.error(err);
      });
  }

  private handlePanelsConfig(layouts: Array<any>) {
    const panels = this.config.panels;
    Object.keys(panels).forEach(name => {
      const panel = {
        name,
        config: null
      };
      const panelEl = panels[name];
      const layoutEl = layouts.find(l => l.title === panelEl.layoutID);
      if (!Tsrv.noValue(layoutEl)) {
        const layout = Tsrv.utils.isJSONString(layoutEl['fun_config'])
          ? JSON.parse(layoutEl['fun_config'])
          : layoutEl['fun_config'];
        const layoutConfig = layout?.layoutConfig;
        const comps = panelEl.comps;
        this.handleLayoutConfig(layoutConfig, comps);
        panel.config = layoutConfig;
        this.panels.push(panel);
      }
    });
  }

  private handleLayoutConfig(layoutConfig: any, comps: Array<any>) {
    if (Tsrv.noValue(layoutConfig)) return;
    const config = layoutConfig;
    if (config['type'] === 'comp') {
      const find = comps.find(c => c.cellID === config['name']);
      if (!Tsrv.noValue(find)) {
        config['name'] = find['type'];
        config['config'] = find;
      }
    }
    if (config['type'] === 'layout') {
      const { first, second } = config['config'] || {};
      if (!Tsrv.noValue(first)) {
        this.handleLayoutConfig(first, comps);
      } else {
        console.error('layoutConfig first is null');
      }
      if (!Tsrv.noValue(first)) {
        this.handleLayoutConfig(second, comps);
      } else {
        console.error('layoutConfig second is null');
      }
    }
  }

  private onEvent(e: any) {}

  destroyed() {
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    /* 最终应用组件销毁 */
    /* this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName,'funName'); */

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `${this.G_compName}`
      ]);
    }
    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null

    this.$bus.$off(this.busEvent.deputy);
  }
}
</script>
<style lang="scss" scoped>
.unitepanel-container {
  width: 100%;
  height: 100%;
  .unite-panel {
    width: 100%;
    height: 100%;
    ::v-deep .ivu-tabs {
      height: 100%;
      .ivu-tabs-bar {
        margin-bottom: 0;
      }
      .ivu-tabs-content {
        height: calc(100% - 34px);
      }
    }
    ::v-deep .ivu-collapse {
      // height: 100%;
      .ivu-collapse-item {
        // height: 100%;
        .ivu-collapse-content {
          // height: 100%;
          .ivu-collapse-content-box {
            height: var(--collapseHeight);
          }
        }
      }
    }
  }
}
</style>
